// 全局响应拦截器： 只针对return的结果有效，使用res.send不会改变响应结构
import { Injectable, NestInterceptor } from '@nestjs/common';
import type { CallHandler } from '@nestjs/common';
import type { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
interface Data<T> {
  data: T;
}
@Injectable()
export class Response<T = any> implements NestInterceptor {
  intercept(context, next: CallHandler): Observable<Data<T>> {
    return next.handle().pipe(
      map((data) => {
        if (Object.prototype.toString.call(data) === '[object Object]') {
          return {
            code: 0,
            status: 0,
            msg: 'success',
            ...data,
          };
        } else {
          return {
            data,
            code: 0,
            status: 0,
            msg: 'success',
          };
        }
      }),
    );
  }
}
